package com.djdevs.calculatorconverter;

import com.djdevs.calculatorconverter.util.SystemUiHider;

import android.R.integer;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;

import java.io.IOException;
import java.io.InputStream;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.xmlpull.v1.XmlPullParserException;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 *
 * @see SystemUiHider
 */
public class FullscreenActivity extends Activity {

	private boolean _resultMode = false;
	private boolean numericReplace = false;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _resultMode = false;
        setContentView(R.layout.activity_fullscreen);
        SetBackSpaceOnClickListener();
        SetNumericButtonListener();
        SetBracesOnClickListener();
        SetDotOnClickListener();
        SetPlusMinusOnClickListener();
        SetPlusOnClickListener();
        SetMinusOnClickListener();
        SetMultiplyOnClickListener();
        SetDivideOnClickListener();
        SetEXPOnClickListener();
        SetSquareRootOnClickListener();
        SetCOnClickListener();
        SetCEOnClickListener();
        SetEqualsOnClickListener();
        int eventType = -1;
//        try
//        {
//        	XmlResourceParser xrpConverter = getResources().getXml(R.xml.converter);
//        	ReadXml rx = new ReadXml(xrpConverter);
//        	ArrayList<String> unitList = rx.GetUnitListForConverter("Length");
//        }
//    	catch (Exception e) {
//			e.printStackTrace();
//		} 

//        ConverterParser cp = new ConverterParser();
//        cp.SetBaseUnit("Metre", "m", 0.0, 1.0);
//        cp.SetFirstUnit("Centimetre", "cm", 100000.0, 0.01);
//        cp.SetSecondUnit("Parsec", "pc", 0.0, 30856775800000000.0);
//        cp.ConvertUnit();
//        Double d = cp.getSecondUnitValue();
//        Double b = d;
    }
    
    private void SetEqualsOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnEquals);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	RunEquals();
            }
        });
    }
    
    private void RunEquals()
    {
    	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
    	String txtList = etCalcList.getText().toString();
    	String result = "";
    	double dblResult = 0.0;
    	
    	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
    	String txt = etCalc.getText().toString();
    	
    	int openCounter = CountCharInString(txtList, '(');
    	int closeCounter = CountCharInString(txtList, ')');
    	
    	if (!txt.equalsIgnoreCase("0")) {
        	if (txt.startsWith("-") || txt.startsWith("√")) {
    			txt = "(" + txt + ")";
    			txtList = txtList + txt;
    		}
        	else
        	{
        		txtList = txtList + txt;
        	}
    	}
    	
    	if (openCounter > closeCounter) {
			int count = openCounter - closeCounter;
			while (count > 0) {
				txtList = txtList + ")";
				count--;
			}
		}
    	
    	if (txtList.indexOf("(") != -1) {
    		result = CalculatorParser.CalculateBraces(txtList, txtList.indexOf("("));
    		if (result.indexOf("(") == -1 && result.indexOf(")") == -1 && CalculatorParser.IfOperatorExists(result)) {
				dblResult = CalculatorParser.evaluate(result);
				result = "" + dblResult;
    		}
		}
    	else {
    		dblResult = CalculatorParser.evaluate(txtList);
    		result = dblResult + "";
		}
    	_resultMode = true;
    	numericReplace = true;
    	etCalcList.setText(txtList);
    	etCalc.setText(result);
    }
    
    private void SetCOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnC);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	_resultMode = false;
            	etCalc.setText(R.string.NUMERIC_0);
            	etCalcList.setText("");
            }
        });
    }
    
    private void SetCEOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnCE);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	etCalc.setText(R.string.NUMERIC_0);
            	_resultMode = false;
            }
        });
    }
    
    private void SetEXPOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnExp);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	
            	String txtList = etCalcList.getText().toString();
            	String txt = etCalc.getText().toString();
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (txt.equalsIgnoreCase("0")) {
            		if (!txtList.endsWith(")")) {
            			txtList = ReplaceNumericOperator(txtList, "-", "^");
                		txtList = ReplaceNumericOperator(txtList, "*", "^");
                		txtList = ReplaceNumericOperator(txtList, "/", "^");
                		txtList = ReplaceNumericOperator(txtList, "+", "^");
					}
            		else {
            			txtList = txtList + "^";
					}
				}
            	else {
            		if (txt.startsWith("-") || txt.startsWith("√")) {
            			txt = "(" + txt + ")";
    				}
            		
            		if (!txtList.endsWith(")")) {
            			txtList = txtList + txt + "^";
            		}
            		else {
            			txtList = txtList + "^";
					}
				}
            	numericReplace = true;
            	etCalcList.setText(txtList);
            	//etCalc.setText(R.string.NUMERIC_0);
            }
        });
    }
    
    private void SetPlusOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnPlus);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	
            	String txtList = etCalcList.getText().toString();
            	String txt = etCalc.getText().toString();
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (txt.equalsIgnoreCase("0")) {
            		if (!txtList.endsWith(")")) {
            			txtList = ReplaceNumericOperator(txtList, "-", "+");
                		txtList = ReplaceNumericOperator(txtList, "*", "+");
                		txtList = ReplaceNumericOperator(txtList, "/", "+");
                		txtList = ReplaceNumericOperator(txtList, "^", "+");
					}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	else {
            		if (txt.startsWith("-") || txt.startsWith("√")) {
            			txt = "(" + txt + ")";
    				}
            		
            		if (!txtList.endsWith(")")) {
            			txtList = txtList + txt + btn.getText();
            		}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	numericReplace = true;
            	etCalcList.setText(txtList);
            	//etCalc.setText(R.string.NUMERIC_0);
            }
        });
    }
    
    private void SetMinusOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnMinus);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	
            	String txtList = etCalcList.getText().toString();
            	String txt = etCalc.getText().toString();
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (txt.equalsIgnoreCase("0")) {
            		if (!txtList.endsWith(")")) {
            			txtList = ReplaceNumericOperator(txtList, "+", "-");
                		txtList = ReplaceNumericOperator(txtList, "*", "-");
                		txtList = ReplaceNumericOperator(txtList, "/", "-");
                		txtList = ReplaceNumericOperator(txtList, "^", "-");
					}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	else {
            		if (txt.startsWith("-") || txt.startsWith("√")) {
            			txt = "(" + txt + ")";
    				}
            		if (!txtList.endsWith(")")) {
            			txtList = txtList + txt + btn.getText();
            		}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	numericReplace = true;
            	etCalcList.setText(txtList);
            	//etCalc.setText(R.string.NUMERIC_0);
            }
        });
    }
    
    private void SetMultiplyOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnMultiply);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	
            	String txtList = etCalcList.getText().toString();
            	String txt = etCalc.getText().toString();
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (txt.equalsIgnoreCase("0")) {
            		if (!txtList.endsWith(")")) {
            			txtList = ReplaceNumericOperator(txtList, "+", "*");
                		txtList = ReplaceNumericOperator(txtList, "-", "*");
                		txtList = ReplaceNumericOperator(txtList, "/", "*");
                		txtList = ReplaceNumericOperator(txtList, "^", "*");
					}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	else {
            		if (txt.startsWith("-") || txt.startsWith("√")) {
            			txt = "(" + txt + ")";
    				}
            		if (!txtList.endsWith(")")) {
            			txtList = txtList + txt + btn.getText();
            		}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	numericReplace = true;
            	etCalcList.setText(txtList);
            	//etCalc.setText(R.string.NUMERIC_0);
            }
        });
    }
    
    private void SetDivideOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnDivision);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	
            	String txtList = etCalcList.getText().toString();
            	String txt = etCalc.getText().toString();
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (txt.equalsIgnoreCase("0")) {
            		if (!txtList.endsWith(")")) {
            			txtList = ReplaceNumericOperator(txtList, "+", "/");
                		txtList = ReplaceNumericOperator(txtList, "-", "/");
                		txtList = ReplaceNumericOperator(txtList, "*", "/");
                		txtList = ReplaceNumericOperator(txtList, "^", "/");
					}
            		else {
            			txtList = txtList + btn.getText();
					}
            		
				}
            	else {
            		if (txt.startsWith("-") || txt.startsWith("√")) {
            			txt = "(" + txt + ")";
    				}
            		if (!txtList.endsWith(")")) {
            			txtList = txtList + txt + btn.getText();
            		}
            		else {
            			txtList = txtList + btn.getText();
					}
				}
            	numericReplace = true;
            	etCalcList.setText(txtList);
            	//etCalc.setText(R.string.NUMERIC_0);
            }
        });
    }
    
    private String ReplaceNumericOperator(String calcEquation, String op1, String op2)
    {
    	if (calcEquation.endsWith(op1)) {
			return calcEquation.substring(0, calcEquation.length() - 1).concat(op2);
		}
    	return calcEquation;
    }
    
    private void SetPlusMinusOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnPlusMinus);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	if (!txt.equalsIgnoreCase("0")) {
	            	if (txt.startsWith("-")) {
						txt = txt.substring(1);
					}
	            	else {
						txt = "-" + txt;
						
					}
            	}
            	
            	etCalc.setText(txt);
            }
        });
    }
    
    private void SetSquareRootOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnSquareRoot);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	
        		TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	String txtList = etCalcList.getText().toString();
            	
            	if (_resultMode) {
            		txtList = "";
            		_resultMode = false;
				}
            	if (!txt.equalsIgnoreCase("0")) {
	            	if (txt.startsWith("√")) {
						txt = txt.substring(1);
					}
	            	else {
						txt = "√" + txt;
						
					}
            	}
            	
            	etCalc.setText(txt);
            	numericReplace = true;
            	etCalcList.setText(txtList);
            }
        });
    }

    
    private void SetBackSpaceOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnBckSpc);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	txt = txt.substring(0, txt.length() - 1);
            	etCalc.setText(txt);
            }
        });
    }
    
    private void SetDotOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnDot);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	if (txt.indexOf(".") == -1) {
            		txt = txt + btn.getText();
            		etCalc.setText(txt);
				}
            }
        });
    }
    
    private void SetBracesOnClickListener()
    {
    	final Button btn = (Button)findViewById(R.id.btnOpenBraces);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	String txtList = etCalcList.getText().toString();
            	if (txtList.endsWith("+") || txtList.endsWith("-") || txtList.endsWith("*") 
            			|| txtList.endsWith("/") || txtList.endsWith("(") || txtList == "") {
					// Append Directly
            		txtList = txtList + btn.getText();
            		etCalcList.setText(txtList);
				}
            }
        });
        
        final Button btnClose = (Button)findViewById(R.id.btnCloseBraces);
        btnClose.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
            	String txtList = etCalcList.getText().toString();
            	
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	
            	int openCounter = CountCharInString(txtList, '(');
            	int closeCounter = CountCharInString(txtList, ')');
            	if (openCounter > closeCounter && txtList.indexOf("(") != -1) {
					//if (txtList.charAt(txtList.length() - 1) != '(') {
						if (!txt.equalsIgnoreCase("0")) {
							txtList = txtList + txt + btnClose.getText();
							etCalcList.setText(txtList);
							etCalc.setText(R.string.NUMERIC_0);
						}
						else {
							txtList = txtList + btnClose.getText();
							etCalcList.setText(txtList);
							etCalc.setText(R.string.NUMERIC_0);
						}
					//}
				}
            }
        });
    }
    
    private int CountCharInString(String str, char c)
    {
    	int counter = 0;
    	for( int i=0; i<str.length(); i++ ) {
    	    if( str.charAt(i) == c ) {
    	        counter++;
    	    } 
    	}
    	
    	return counter;
    }
    
    private void SetNumericButtonListener()
    {
    	SetNumericButtonOnClickListener(R.id.btn0);
    	SetNumericButtonOnClickListener(R.id.btn1);
    	SetNumericButtonOnClickListener(R.id.btn2);
    	SetNumericButtonOnClickListener(R.id.btn3);
    	SetNumericButtonOnClickListener(R.id.btn4);
    	SetNumericButtonOnClickListener(R.id.btn5);
    	SetNumericButtonOnClickListener(R.id.btn6);
    	SetNumericButtonOnClickListener(R.id.btn7);
    	SetNumericButtonOnClickListener(R.id.btn8);
    	SetNumericButtonOnClickListener(R.id.btn9);
    }
    
    private void SetNumericButtonOnClickListener(int id)
    {
    	final Button btn = (Button)findViewById(id);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	TextView etCalc = (TextView)findViewById(R.id.txtCalc);
            	String txt = etCalc.getText().toString();
            	
        		TextView etCalcList = (TextView)findViewById(R.id.txtCalcList);
        		//String txtList = etCalcList.getText().toString();
            	
            	//Editable eTxt = etCalc.getText();
            	if (txt.equalsIgnoreCase("0")) {
            		txt = "";
				}
            	
            	if (numericReplace) {
            		numericReplace = false;
            		txt = "";
				}
            	
            	txt = txt + btn.getText();
            	etCalc.setText(txt);
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
//        delayedHide(100);
    }
}
